const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const foot = require('../../templates/foot/index.js');
const wxParser = require('../../wxParser/index');
var loginStatus = wx.getStorageSync("loginStatus");
const {
  $Toast
} = require('../../components/base/base');
var tabBar = foot.tabBar;
var tabBarList = [];
var cartVal = [];

Page({

  data: {
    navBg: app.globalData.navBg,
    navColor: app.globalData.navColor,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    navTop: app.globalData.navHeight,
    back: false,
    navBox: false,
    tabBar: [],
    checkAll: false,
    totalCount: 0,
    totalPrice: 0,
    hasList: true,
    cart: [], //数据
    Num: 1, //商品数量默认是1
    total: 0, //总金额
    goodsCount: 0, //数量
    management_good: false,
    disabled: true,
    allSelect: true,
    noSelect: false,
    goTop: true,
    scrollHeight: app.globalData.windowHeight - app.globalData.navHeight - 140
  },

  toIndexBtn: function () {
    util.navigateTo('../index/index')
  },

  //计算商品总数
  calculateTotal: function (e) {
    var that = this;
    var cart = this.data.cart;
    var totalCount = 0;
    var totalNumber = 0;
    var totalPrice = 0;
    for (var i = 0; i < cart.length; i++) {
      var good = cart[i];
      if (good.IsSel) {
        totalCount += good.Num;
        totalPrice += good.Num * good.Price;
      }
      totalNumber += parseInt(good.Num);
    }
    totalPrice = totalPrice.toFixed(2);
    that.setData({
      totalCount: totalCount,
      totalPrice: totalPrice
    })

  },

  // 加入收藏
  collectitem: function (e) {
    var that = this;
    var arr = wx.getStorageSync('shopCart') || [];
    var arr2 = [];
    var atr = [];
    var collect = wx.getStorageSync('shopCollect') || [];
    var results = [];
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
      var checks = arr[i].IsSel // 获取当前缓存商品的状态
      atr.push(checks)
    }
    if (atr.includes(false) && !atr.includes(true)) {

      $Toast({
        content: "请选择商品!",
        icon: 'prompt_fill',
        duration: 1
      });
    } else {
      wx.showModal({
        title: '',
        confirmText: "确定",
        confirmColor: "#e93b3d",
        cancelText: "取消",
        cancelColor: "#333",
        content: '您确定要加入收藏吗？',
        success: function (res) {
          if (res.confirm) {
            var cart = that.data.cart;
            for (var i = 0; i < cart.length; i++) {
              var curItem = cart[i];
              if (curItem.IsSel) {
                try {
                  curItem.Num = 1;
                  curItem.IsSel = true;
                  collect.push(curItem)
                  for (var j = 0; j < collect.length; j++) {
                    if (!obj[collect[j].id]) {
                      results.push(collect[j]);
                      obj[collect[j].id] = true;
                    }
                  }

                  that.setGoodsCollect(that.allSelect(), that.noSelect(), results);
                  setTimeout(() => {
                    $Toast({
                      content: "加入收藏成功！",
                      icon: 'success',
                      duration: 1
                    });
                  }, 600);
                } catch (e) {

                }


              }
            }

          } else if (res.cancel) {

          }
        }
      })
    }
  },

  // 批量删除
  deleteitem: function (e) {
    var that = this;
    var arr = wx.getStorageSync('shopCart') || [];
    var arr2 = [];
    var atr = [];
    for (var i = 0; i < arr.length; i++) {
      var checks = arr[i].IsSel // 获取当前缓存商品的状态
      atr.push(checks)
    }
    //根据缓存商品状态判断当前商品是否选中
    if (atr.includes(false) && !atr.includes(true)) {

      $Toast({
        content: "请选择商品!",
        icon: 'prompt_fill',
        duration: 1
      });
    } else {
      //console.log(that.data.ShopcartProductIDs)
      wx.showModal({
        title: '',
        confirmText: "删除",
        confirmColor: "#e93b3d",
        cancelText: "取消",
        cancelColor: "#333",
        content: '您确定要删除吗？',
        success: function (res) {
          if (res.confirm) {
            var cart = that.data.cart;
            for (var i = 0; i < cart.length; i++) {
              var curItem = cart[i];
              if (curItem.IsSel) {
                var cart = that.data.cart;
                cart.splice(i--, 1);
                that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
                
                wx.request({
                  url: util.api + api.DeleteCart,
                  data: {
                    BUSINESS_PARAMETERS: {
                      userToekn: loginStatus.token,
                      PostStaId: 22,
                      ShopcartProductIDs: that.data.ShopcartProductIDs
                    },
                    SYSTEM_PARAMETERS: {
                      APP_ID: "M_P_G001",
                      METHOD_ID: 0,
                      ACCESS_TOKEN: "1w2Re3bE^og38",
                      TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
                      SIGN: "string"
                    }
                  },
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/json'
                  },
                  success: function (res) {
                    if (!cart.length) {
                      that.setData({
                        hasList: false,
                        checkAll: false,
                        totalPrice: 0
                      });
                    }
                    setTimeout(() => {
                      $Toast({
                        content: "删除成功！",
                        icon: 'success',
                        duration: 1
                      });
                    }, 600);
                  },
                  fail: function (res) {
                    
                  }

                })

              }
            }

          } else if (res.cancel) {

          }
        }
      })
    }
  },

  //点击商品减1
  minCart: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    var cart = that.data.cart;
    if (index !== "" && index != null) {
      if (cart[parseInt(index)].Num > 1) {
        cart[parseInt(index)].Num--;
        that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
      } else {
        wx.showModal({
          title: '',
          confirmText: "删除",
          confirmColor: "#e93b3d",
          cancelText: "取消",
          cancelColor: "#333",
          content: '您确定要删除吗？',
          success: function (res) {
            if (res.confirm) {
              cart.splice(index, 1);
              that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
              if (!cart.length) {
                that.setData({
                  hasList: false,
                  checkAll: false,
                  totalPrice: 0
                });
              } else { // 如果不为空
                that.calculateTotal(); // 重新计算总价格
              }
              setTimeout(() => {
                $Toast({
                  content: "删除成功！",
                  icon: 'success',
                  duration: 1
                });
              }, 600);
            } else if (res.cancel) {

            }
          }
        })
      }
    }

  },

  //点击商品加1
  plusCart: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cart;
    if (index !== "" && index != null) {
      cart[parseInt(index)].Num++;
      cart[parseInt(index)].IsSel = true;
      that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
      var Nums = 1;
      var goodID = cart[parseInt(index)].ProductId;
      var plusGood = true;
      that.addCart(Nums,goodID,plusGood)
    }
  },

  // 监听输入
  cartNum: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = that.data.cart;
    var Nums = e.detail.value - cart[parseInt(index)].Num;
          var goodID = cart[parseInt(index)].ProductId;
          var plusGood = true;
          that.addCart(Nums,goodID,plusGood)
          //console.log(cart)
    //return
    
    
  },

  allSelect: function () {
    var cart = this.data.cart;
    var allSelect = false;
    for (var i = 0; i < cart.length; i++) {
      var curItem = cart[i];
      if (curItem.IsSel) {
        allSelect = true;
      } else {
        allSelect = false;
        break;
      }
    }
    return allSelect;
  },

  noSelect: function () {
    var cart = this.data.cart;
    var noSelect = 0;
    for (var i = 0; i < cart.length; i++) {
      var curItem = cart[i];
      if (!curItem.IsSel) {
        noSelect++;
      }
    }
    if (noSelect == cart.length) {
      return true;
    } else {
      return false;
    }
  },

  setGoodsList: function (total, allSelect, noSelect, cart) {
    this.setData({
      allSelect: allSelect,
      noSelect: noSelect,
      cart: cart
    });
    wx.setStorage({
      key: "shopCart",
      data: cart
    })
  },

  setGoodsCollect: function (allSelect, noSelect, cart) {
    this.setData({
      allSelect: allSelect,
      noSelect: noSelect
    });
    wx.setStorage({
      key: "shopCollect",
      data: cart
    })
  },

  // 选择购物车商品
  checkboxChange: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var cart = this.data.cart;
    if (index !== "" && index != null) {
      cart[parseInt(index)].IsSel = !cart[parseInt(index)].IsSel;
      that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), cart);
    }
    let str = true; //用str与每一项进行状态判断        
    for (var i = 0; i < cart.length; i++) {
      str = str && cart[i].IsSel; //用str与每一项进行状态判断
    }
    if (str === true) {
      that.setData({
        checkAll: true
      })
    } else {
      that.setData({
        checkAll: false
      })
    }
    wx.request({
      url: util.api + api.SetCartIsSel,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          ShopcartProductIDs: that.data.ShopcartProductIDs,
          check: true
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        
      },
      fail: function (res) {
        
      }

    })
    // console.log(e)
  },

  //全选
  selectalltap: function (e) {
    var that = this;
    var checkAll = !this.data.checkAll;
    var cart = this.data.cart;
    let arr2 = [];
    if (checkAll) {
      for (var i = 0; i < cart.length; i++) {
        cart[i].IsSel = true;
        arr2.push(cart[i]);
      }
    } else {
      for (var i = 0; i < cart.length; i++) {
        cart[i].IsSel = false;
        arr2.push(cart[i]);
      }
    }
    that.setData({
      checkAll: checkAll
    });
    that.setGoodsList(that.calculateTotal(), !checkAll, that.noSelect(), cart);
  },

  checkChange: function (e) {
    var that = this;
    var value = e.detail.value
    if (value.length != 0) {
      that.setData({
        disabled: false,
        ShopcartProductIDs: value
      })
    } else {
      that.setData({
        disabled: true
      })
    }
    
    cartVal = value
    // console.log(value)
    const resultsGood = [];
    const resultsNum = [];
    for(let i=0;i<value.length;i++){
      var productId = value[i].split(",")[0].split(",");
      var productNum = value[i].split(",")[1].split(",");
      for (let j = 0; j < productId.length; j++) {
        resultsGood.push(productId[j])
      }
      for (let k = 0; k < productNum.length; k++) {
        resultsNum.push(productNum[k])
      }
    }
    console.log(resultsGood)
    console.log(resultsNum)
  },

  checkChangeAll: function (e) {
    var that = this;
    var value = e.detail.value
    if (value.length != 0) {
      that.setData({
        disabled: false,
        ShopcartProductIDs: value
      })
    } else {
      that.setData({
        disabled: true
      })
    }
    console.log(cartVal)
  },

  // 管理商品
  management: function () {
    let that = this;
    that.setData({
      management_good: true,
    })
  },

  finish_management: function () {
    let that = this;
    that.setData({
      management_good: false,
    })
  },

  gotoDetail: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    util.navigateTo('../productdetail/productdetail?id=' + id)
  },

  toconfirm: function () {
    util.navigateTo('../orderConfirm/orderConfirm')
  },

  // 加入或修改购物车
  addCart: function (Nums,goodID,plusGood) {
    var that = this;
    wx.request({
      url: util.api + api.AddOrModCart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          ProductIDs: [goodID],
          nums: [Nums],
          plus: plusGood
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.cartNumber(Nums,plusGood);
        // console.log("加入购物车成功!")
        wx.request({
          url: util.api + api.GetShopcart,
          data: {
            BUSINESS_PARAMETERS: {
              userToekn: loginStatus.token,
              PostStaId: 22
            },
            SYSTEM_PARAMETERS: {
              APP_ID: "M_P_G001",
              METHOD_ID: 0,
              ACCESS_TOKEN: "1w2Re3bE^og38",
              TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
              SIGN: "string"
            }
          },
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
            if (res.data.MESSAGE.MESSAGE_CODE == 1) {
              that.setData({
                cart: res.data.RESULT
              })
              console.log(res.data.RESULT)
            }
    
          },
          fail: function (res) {}
        })
      },
      fail: function (res) {}

    })

  },

  // 单个删除购物车
  deleteCart: function (Nums,goodID) {
    var that = this;
    // var pid = e.currentTarget.dataset.id;
    // var id = [];
    // id.push(pid)
    // console.log(Nums)
    // console.log(goodID)
    return
    that.cartNumber(Nums,plusGood);
    
    wx.request({
      url: util.api + api.AddOrModCart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22,
          ShopcartProductIDs: []
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // $Toast({
        //   content: "加入购物车成功!",
        //   icon: 'success',
        //   duration: 1
        // });
        console.log("加入购物车成功!")
      },
      fail: function (res) {}

    })

  },

  //加入购物车实时数量
  cartNumber: function (Nums,plusGood) {
    var that = this;
    var cart = that.data.cart;
    var counts = 0;
    //console.log(Nums)
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts += parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {}
    })
  },

  //页面加载时购物车数量
  countCart: function (e) {
    var that = this;
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        if (res.data.MESSAGE.MESSAGE_CODE == 1) {
          var arr = res.data.RESULT || [];
          var counts = 0;
          //遍历购物车对其进行求和
          for (var i = 0; i < arr.length; i++) {
            counts = parseInt(counts) + parseInt(arr[i].Num);
          }
          let navCont = that.data.navCont;
          console.log(arr)
          //购物车商品数量
          that.setData({
            navCont: counts
          })
        }

      },
      fail: function (res) {
        that.setData({
          showSkeleton: false
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    this.calculateTotal();
    for (let i = 0; i < tabBar.length; i++) {
      tabBar[0].style = 0;
      tabBar[1].style = 0;
      tabBar[2].style = 0;
      tabBar[3].style = 1;
      tabBar[4].style = 0;
      tabBar[3].ico = 1;
      tabBarList.push(tabBar[i])
    }
    that.setData({
      tabBar: tabBarList
    })
    tabBarList.length = 0;
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    this.countCart();
    this.cartNumber();
    wx.request({
      url: util.api + api.GetShopcart,
      data: {
        BUSINESS_PARAMETERS: {
          userToekn: loginStatus.token,
          PostStaId: 22
        },
        SYSTEM_PARAMETERS: {
          APP_ID: "M_P_G001",
          METHOD_ID: 0,
          ACCESS_TOKEN: "1w2Re3bE^og38",
          TIMESTAMP: util.formatTime(new Date(), 'Y/M/D h:m:s'),
          SIGN: "string"
        }
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        that.setData({
          cart: res.data.RESULT
        })
        //console.log(res.data.RESULT)
      },
      fail: function (res) {}

    })

    /*
    // 获取产品展示页保存的缓存数据（购物车的缓存数组，没有数据，则赋予一个空数组）
    var arr = wx.getStorageSync('shopCart') || [];
    // 有数据的话，就遍历数据，计算总金额 和 总数量
    if (arr.length > 0) {
      that.data.cart = arr;
      that.setGoodsList(that.calculateTotal(), that.allSelect(), that.noSelect(), arr);
      for (var i in arr) {
        that.data.total += Number(arr[i].price) * Number(arr[i].count);
        that.data.goodsCount += Number(arr[i].count);
      }
      // 更新数据
      that.setData({
        hasList: true,
        cart: arr,
        total: that.data.total,
        goodsCount: that.data.goodsCount
      });

      //判断全选按钮状态
      var atr = [];
      for (var i = 0; i < arr.length; i++) {
        var checks = arr[i].checked // 获取当前缓存商品的状态
        atr.push(checks)
        if (arr[i].checked == true) {
          that.setData({
            disabled: false
          });
        } else {
          that.setData({
            disabled: true
          });
        }
      }

      if (atr.includes(false)) { //判断是否存在false
        that.setData({
          checkAll: false
        })

      } else {
        that.setData({
          checkAll: true
        })
      }

      var found = false;
      for (var i = 0; i < arr.length; i++) {
        var checks = arr[i].checked // 获取当前缓存商品的状态
        if (arr[i].checked == true) {
          that.setData({
            disabled: false
          });
          found = true;
          break;
        } else {
          that.setData({
            disabled: true
          });
        }
      }

    } else {
      that.setData({
        hasList: false
      });
    }*/
  },

  scroll: function (e) {
    var that = this;
    var listIndex = (e.detail.scrollTop + this.data.screenHeight) / (this.data.screenWidth * 0.4)
    if (e.detail.scrollTop > app.globalData.navHeight + 40) {
      this.setData({
        goTop: false
      });
      this.setData({
        listIndex: listIndex
      })
    } else {
      this.setData({
        goTop: true
      });
    }

  },

  //返回顶部
  goScrolltop: function (e) {
    var that = this;
    var top = that.data.scrollTop;
    if (top == 1) {
      top = 0;
    } else {
      top = 1;
    }

    that.setData({
      scrollTop: top
    })

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }


})